//
//  FaceRegisterViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/4.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "FaceRegisterViewController.h"
#import "FaceRegisterConfirmViewController.h"
@interface FaceRegisterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong) UIImageView *photoView;
@property(nonatomic,strong) UIImageView *videoView;
@property(nonatomic,strong) UIButton *photoButton;
@property(nonatomic,strong) UIButton *videoButton;
@property(nonatomic,strong) UIImagePickerController *imagePicker;

@end

@implementation FaceRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark --- 点击事件
- (void)didClickPhotoButton
{
    [self pushToPickerView:(NSString *)kUTTypeImage];
}

- (void)didClickVideoButton
{
    [self pushToPickerView:(NSString *)kUTTypeMovie];
}


#pragma mark --- 事件处理
- (void)pushToPickerView:(NSString *)type
{
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.mediaTypes = @[type];
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
//    FaceRegisterConfirmViewController *vc = [FaceRegisterConfirmViewController new];
//    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ---- 代理
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        // video url:
        // file:///private/var/mobile/Applications/B3CDD0B2-2F19-432B-9CFA-158700F4DE8F/tmp/capture-T0x16e39100.tmp.9R8weF/capturedvideo.mp4
        // we will convert it to mp4 format
        NSURL *mp4 = [self _convert2Mp4:videoURL];
        NSFileManager *fileman = [NSFileManager defaultManager];
        if ([fileman fileExistsAtPath:videoURL.path]) {
            NSError *error = nil;
            [fileman removeItemAtURL:videoURL error:&error];
            if (error) {
                NSLog(@"failed to remove file, error:%@.", error);
            }
        }
        [[DataManager sharedInstance] sendVideoWithURL:mp4];

    }else{
        NSURL *url = info[UIImagePickerControllerReferenceURL];
        if (url == nil) {
            UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
            NSData * imageData = UIImageJPEGRepresentation(orgImage, 1.0f);
            [[DataManager sharedInstance] sendImageWithData:imageData];
        }
        else
        {
            UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
            NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
            [[DataManager sharedInstance] sendImageWithData:imageData];
        }

        

//        NSURL *url = info[UIImagePickerControllerReferenceURL];
//        if (url == nil) {
//            UIImage *orgImage = info[UIImagePickerControllerOriginalImage];
//            [self sendImageMessage:orgImage];
//        } else {
//            if ([[UIDevice currentDevice].systemVersion doubleValue] >= 9.0f) {
//                PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
//                [result enumerateObjectsUsingBlock:^(PHAsset *asset , NSUInteger idx, BOOL *stop){
//                    if (asset) {
//                        [[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData *data, NSString *uti, UIImageOrientation orientation, NSDictionary *dic){
//                            if (data != nil) {
//                                [self sendImageMessageWithData:data];
//                            } else {
//                                [self showHint:NSEaseLocalizedString(@"message.smallerImage", @"The image size is too large, please choose another one")];
//                            }
//                        }];
//                    }
//                }];
//            } else {
//                ALAssetsLibrary *alasset = [[ALAssetsLibrary alloc] init];
//                [alasset assetForURL:url resultBlock:^(ALAsset *asset) {
//                    if (asset) {
//                        ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
//                        Byte* buffer = (Byte*)malloc((size_t)[assetRepresentation size]);
//                        NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:0.0 length:(NSUInteger)[assetRepresentation size] error:nil];
//                        NSData* fileData = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
//                        [self sendImageMessageWithData:fileData];
//                    }
//                } failureBlock:NULL];
//            }
//        }
    }

    [picker dismissViewControllerAnimated:YES completion:nil];

    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:NO];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:NO];
}

/*!
 @method
 @brief mov格式视频转换为MP4格式
 @discussion
 @param movUrl   mov视频路径
 @result  MP4格式视频路径
 */
- (NSURL *)_convert2Mp4:(NSURL *)movUrl
{
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", [EMCDDeviceManager dataPath], (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
        mp4Url = [NSURL fileURLWithPath:mp4Path];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}

#pragma mark --- 懒加载
- (UIImageView *)photoView
{
    if(!_photoView)
    {
        UIView *superView = self.view;
        _photoView = [[UIImageView alloc]init];
        [superView addSubview:_photoView];
        _photoView.image = [UIImage imageNamed:@"picture"];
    }
    return _photoView;
}
- (UIImageView *)videoView
{
    if(!_videoView)
    {
        UIView *superView = self.view;
        _videoView = [[UIImageView alloc]init];
        [superView addSubview:_videoView];
        _videoView.image = [UIImage imageNamed:@"video1"];
    }
    return _videoView;
}
- (UIButton *)photoButton
{
    if(!_photoButton)
    {
        UIView *superView = self.view;
        _photoButton = [[UIButton alloc]init];
        [superView addSubview:_photoButton];
        [_photoButton setTitle:@"上传照片" forState:UIControlStateNormal];
        [_photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_photoButton.titleLabel setFont:fontCommonSize];
        [_photoButton setBackgroundColor:rgba(0,159,236,1)];
        _photoButton.layer.cornerRadius = 2;
        [_photoButton addTarget:self action:@selector(didClickPhotoButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _photoButton;
}
- (UIButton *)videoButton
{
    if(!_videoButton)
    {
        UIView *superView = self.view;
        _videoButton = [[UIButton alloc]init];
        [superView addSubview:_videoButton];
        [_videoButton setTitle:@"视频拍摄" forState:UIControlStateNormal];
        [_videoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_videoButton.titleLabel setFont:fontCommonSize];
        [_videoButton setBackgroundColor:rgba(0,159,236,1)];
        _videoButton.layer.cornerRadius = 2;
        [_videoButton addTarget:self action:@selector(didClickVideoButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _videoButton;
}

- (UIImagePickerController *)imagePicker
{
    if (_imagePicker == nil) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.modalPresentationStyle= UIModalPresentationOverFullScreen;
        _imagePicker.delegate = self;
    }
    
    return _imagePicker;
}


- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    [self.photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(322));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.width.mas_equalTo(px1920Height(318));
    }];
    
    [self.photoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.photoView.mas_bottom).with.offset(px1920Height(74));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.mas_equalTo(px1920Height(113));
        make.width.mas_equalTo(px1080Width(318));
    }];
    
    [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.photoButton.mas_bottom).with.offset(px1920Height(170));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.width.mas_equalTo(px1920Height(318));
    }];
    
    [self.videoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.videoView.mas_bottom).with.offset(px1920Height(74));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.height.mas_equalTo(px1920Height(113));
        make.width.mas_equalTo(px1080Width(318));
    }];
}


- (void)setNavigationStyle
{
    [self setNavigationBarTitle:@"人脸识别注册"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
